package com.wuseguang.springcloud.service.impl;

import com.wuseguang.springcloud.dao.jdbc.RoleDataPermissionsJdbc;
import com.wuseguang.springcloud.dao.repository.RoleDataPermissionsRepository;
import com.wuseguang.springcloud.entity.RoleDataPermissions;
import com.wuseguang.springcloud.service.RoleDataPermissionsService;
import com.wuseguang.springcloud.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色数据权限 服务实现类
 * </p>
 *
 * @author 
 * @since 2019-12-18
 */
@Service
public class RoleDataPermissionsServiceImpl implements RoleDataPermissionsService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RoleDataPermissionsRepository roleDataPermissionsRepository;
    @Autowired
    private RoleDataPermissionsJdbc roleDataPermissionsJdbc;

    @Override
    public Result findRoleDataPermissions(String schoolId, Integer roleId) {

        logger.info("查询角色的数据权限");
        //查询sql
        String sql = "select dp.id,dp.name,if(IFNULL(rdp.id,0) = 0,0,1) state ,rdp.id rdpid from data_permissions dp left join role_data_permissions rdp on(dp.id=rdp.date_permissions_id and rdp.school_id = ? and rdp.role_id = ?)";
        logger.info("查询角色的数据权限 SQL = {}",sql);

        //数据权限集合
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();

        try{
           list = roleDataPermissionsJdbc.queryListMap(sql,schoolId,roleId);
        }catch (Exception e){
            logger.info("查询角色数据权限异常 e",e);
        }

        return new Result(list);
    }

    @Override
    public Result addAndUpdateRoleDataPermissions(String schoolId, Integer roleId, Integer dpid) {

        RoleDataPermissions rdp =  roleDataPermissionsRepository.findRoleIdAndSchoolId(roleId,schoolId);

        if(rdp == null ){
            rdp = new RoleDataPermissions();
            rdp.setRoleId(roleId);
            rdp.setDatePermissionsId(dpid);
            rdp.setSchoolId(Integer.valueOf(schoolId));
        }else{
            rdp.setDatePermissionsId(dpid);
        }

        roleDataPermissionsRepository.save(rdp);

        return new Result();
    }
}
